# -*-coding:utf-8-*-
from AutoWool.main.base.Singleton import Singleton

import pyttsx3

from AutoWool.main.utils.log_utils import Log
from AutoWool.main.utils.system_utils import SystemUtils

if SystemUtils.judgeSystemType() == SystemUtils.SYS_TYPE_WIN:
    import win32com.client
    speaker = win32com.client.Dispatch("SAPI.SpVoice")


class AudioSayUtils(Singleton):

    @staticmethod
    def say(words):
        if SystemUtils.judgeSystemType() == SystemUtils.SYS_TYPE_WIN:
            pattern_obj: BaseAudioSayPattern = Win32Pattern()
        else:
            pattern_obj: BaseAudioSayPattern = PyttsxPattern()
        Log.log('开始读' + str(words))
        pattern_obj.say(words)


class BaseAudioSayPattern:

    def say(self, words):  # 朗读文本(文字转声音)
        pass

    def shut_up(self):  # 关闭朗读
        pass

    def change_say_sound(self):  # 更换发音人声音
        pass

    def get_cur_say_speend(self):  # 获得当前语速
        pass

    def change_say_speed(self, new_rate):  # 语速控制
        pass

    def get_cur_volume(self):  # 获得当前音量
        pass

    def change_say_volume(self, new_volume):  # 音量控制
        pass


class Win32Pattern(BaseAudioSayPattern):

    def say(self, words):  # 朗读文本(文字转声音)
        speaker.Speak(words)

    def shut_up(self):  # 关闭朗读
        pass

    def change_say_sound(self):  # 更换发音人声音
        pass

    def get_cur_say_speend(self):  # 获得当前语速
        pass

    def change_say_speed(self, new_rate):  # 语速控制
        pass

    def get_cur_volume(self):  # 获得当前音量
        pass

    def change_say_volume(self, new_volume):  # 音量控制
        pass


class PyttsxPattern(BaseAudioSayPattern):
    # 声音朗读引擎
    engine = pyttsx3.init()

    def say(self, words):  # 朗读文本(文字转声音)
        PyttsxPattern.engine.say(str(words))
        PyttsxPattern.engine.runAndWait()

    def shut_up(self):  # 关闭朗读
        print('开始关闭朗读')
        PyttsxPattern.engine.stop()

    def change_say_sound(self):  # 更换发音人声音
        voices = PyttsxPattern.engine.getProperty('voices')
        for voice in voices:
            print('voice.id=' + str(voice.id))
            PyttsxPattern.engine.setProperty('voice', voice.id)
            # PyttsxUtils.engine.say('The quick brown fox jumped over the lazy dog.')
        PyttsxPattern.engine.runAndWait()

    def get_cur_say_speend(self):  # 获得当前语速
        return PyttsxPattern.engine.getProperty('rate')

    def change_say_speed(self, new_rate):  # 语速控制
        rate = PyttsxPattern.engine.getProperty('rate')
        PyttsxPattern.engine.setProperty('rate', new_rate)
        # PyttsxUtils.engine.say('The quick brown fox jumped over the lazy dog.')
        PyttsxPattern.engine.runAndWait()

    def get_cur_volume(self):  # 获得当前音量
        return PyttsxPattern.engine.getProperty('volume')

    def change_say_volume(self, new_volume):  # 音量控制
        PyttsxPattern.engine.setProperty('volume', new_volume)
        # PyttsxUtils.engine.say('The quick brown fox jumped over the lazy dog.')
        PyttsxPattern.engine.runAndWait()
